package com.apes.fn.scm.retailOrder.model;

import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.finance.model.CrossIC;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 销售折扣表
 *
 * @author wuq
 * @create 2020-03-14 10:43
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = RetailOrderDiscount.CONST_TABLE_NAME)
public class RetailOrderDiscount extends BaseModel {
    public static final String CONST_TABLE_NAME = "retail_order_discount";

    @Id
    @Column(name = "id")
    @Comment("销售折扣单号")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "销售折扣", prefix = "2")
    private String id;

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "retail_order_id", referencedColumnName = "id")
    @Comment("付款单编码")
    private RetailOrder retailOrder; /*零售单主表*/

    @ManyToOne(optional = false)
    @Comment("销售明细单号")
    @JoinColumn(name="retail_item_id", referencedColumnName="id", nullable = false)
    private RetailOrderItem retailOrderItem;

    @Comment("促销类别")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "discount_type", referencedColumnName = "id")
    private Enumeration discountType;   // 促销类别(001600:折扣;001599:赠送;001602:返现;001601:积分;001598:红包;001597:保障折扣;001622:异业合作;001612:立减优惠;001613:分销优惠)

    @Comment("折扣金额")
    @Column(name = "discount_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double discountAmount = 0;

    @Comment("票券号码")
    @Column(name = "coupon_number")
    private String couponNumber;

    @Comment("票券使用数量")
    @Column(name = "coupon_used_qty")
    private double couponUsedQty;

    @Comment("票券折扣金额")
    @Column(name = "coupon_discount_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double couponDiscountAmount;

    @Comment("票券优惠金额（车主出钱购买的部分）")
    @Column(name = "coupon_profit_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double couponProfitAmount;

    @Column(name = "coupon_Resource", length = 120)
    @Comment("兑换券来源")
    private String couponResource; // 兑换券来源(0：年卡销售；1：保险送赠；2：促销送赠；3：二手车赠送；4：期初导入；5：老业主会员接收；6：免费机油活动赠送；7：人保专用券；8：扫码送券；9：中石化兑换券)

    @Column(name = "coupon_Discount_Type", length = 2, columnDefinition = "NUMBER(1,0) default 0")
    @Comment("兑换券抵扣方式")
    private int couponDiscountType = 0; // 抵扣方式(1:面值抵扣,2全额抵扣)

    @Comment("票券公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "coupon_company_id", referencedColumnName = "id")
    private PartyRole couponCompany;

    @Comment("商户客户")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "coupon_Customer", referencedColumnName = "id")
    private PartyRole couponCustomer;   // 暂时写死为 1001

    @Comment("客户结算价")
    @Column(name = "coupon_Customer_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double couponCustomerPrice;

    @Comment("平台结算价")
    @Column(name = "platform_price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double platformPrice;

    @Column(name = "remark", length = 120)
    @Comment("备注")
    private String remark;


    @Comment("异业合作编码")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "crossIC_id", referencedColumnName = "id")
    private CrossIC crossIC;

    @OneToMany(mappedBy = "retailDiscount", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<RetailOrderDiscountItem> retailDiscountItems = new ArrayList<>();

    public List<RetailOrderDiscountItem> getRetailDiscountItems(){
        if (Objects.isNull(retailDiscountItems))  retailDiscountItems = new ArrayList<>();
        double discountAmounts = 0;
        for (RetailOrderDiscountItem item: retailDiscountItems) {
//            // 2022-01-17 APP 规则 优惠单价大于等于销售价 时，折扣就为0。 ERP 控制不住，为了接受年卡折扣明细，放开控制。 APP 对接人：黄柱杰
//            if (item.getAmount() == 0) throw new RuntimeException("折扣明细存在为 0 的明细，请检查！");
            item.setRetailDiscount(this);

            if (Objects.nonNull(this.retailOrder)) item.setRetailOrderId(this.retailOrder.getId());
            discountAmounts += item.getAmount();
        }
        return retailDiscountItems;
    }

    public void checkDiscountItemAmt(){

        // 促销类别(001600:折扣;001599:赠送;001602:返现;001601:积分;001598:红包;001597:保障折扣;001622:异业合作;001612:立减优惠;001613:分销优惠)
        if (LogicalUtil.in(this.discountType.getId(), "001600", "001598")) {
            double discountItemAmtSum = this.retailDiscountItems.stream().mapToDouble(RetailOrderDiscountItem::getAmount).sum();
            if (this.discountAmount - discountItemAmtSum > 0.0001) {    // 允许存在误差
                throw new RuntimeException("折扣中的金额与折扣明细上面的金额不相等，请检查数据节点 retailDiscounts 下面的 discountAmount 与 retailDiscountItems 的合计值");
            }
        }

        if ("001622".equals(this.discountType.getId()) && this.discountAmount == 0) {
//            throw new RuntimeException("折扣信息中异业合作金额不允许为0，请检查！");
        }

        if (this.discountAmount == 0) return;
    }

    /**
     * 判断当前对象是否为空
     * @return false 为空，true 不为空
     */
    public boolean checkNotEmpty(){
        return this.getDiscountType() != null;
    }


    /**
     * 判断是否为年卡兑换券
     * @return false 为空，true 不为空
     */
    public boolean checkIsYearCard(){
        if(this.couponResource==null){
            return false;
        }
        return this.couponResource.equals("年卡销售");
    }

    /**
     * 判断是否为异业合作
     * @return boolean
     */
    public boolean checkIsCrossIC() {
        // 001622 表示使用 APP折扣（异业部分）， 异业合作存在 CrossIC ， 单位客户挂账不会存在 CrossIC
        return "001622".equals(this.getDiscountType().getId()) && Objects.nonNull(this.getCrossIC());
    }

}
